#pragma once

#include<iostream>
#include<string.h>

#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <sys/types.h>          /* See NOTES */
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */

#include"log.hpp"

log l;

uint16_t Port=8080;
std::string Ip="0.0.0.0";
const int number=20;    //listen监听数量

//网络套接字
class Socket
{
public:
    Socket(std::string ip=Ip,uint16_t port=Port)
    :ip_(ip)
    ,port_(port)
    {}

    void Sock()
    {
        sockfd_=socket(AF_INET,SOCK_DGRAM,0);
        if(sockfd_<0)
        {
            l(err,"errno:%d,strerror:%s",errno,strerror(errno));
            exit(-1);
        }
        l(info,"sockfd文件创建成功");

        memset(&addr_,0,sizeof(addr_));
        addr_.sin_family=AF_INET;
        addr_.sin_addr.s_addr=INADDR_ANY;
        addr_.sin_port=htons(port_);
    }

    void Bind()
    {
        socklen_t len=sizeof(addr_);
        int n=bind(sockfd_,reinterpret_cast<struct sockaddr*> (&addr_),len);
        if(n<0)
        {
            l(err,"bind失败：errno:%d,strerror:",errno,strerror(errno));
            exit(-1);
        } 
        l(info,"bind成功");
    }

    int Listen()
    {
        int n=listen(sockfd_,number);
        if(n<0)
        {
            l(err,"listen开启监听失败:errno:%d,strorror:%s",errno,strerror(errno));
            exit(-1);
        }
        l(info,"listen开启监听成功");

        return n;
    }

    void Accept()
    {
        int listenfd=Listen();

        struct sockaddr_in client;
        socklen_t len=sizeof(client);
        int clientfd=accept(listenfd,(struct sockaddr*) &client,&len);
        if(clientfd<0)
        {
            
        }
    }

private:
    int sockfd_;
    uint16_t port_;
    struct sockaddr_in addr_;
    std::string ip_ ;
};